package com.yx.utils;

import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Classname orderUtils
 * @Date 2021/07/20 19:56
 * @Author by yx
 * @Description TODO:
 */
@Component
public class OrderUtils {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 订单ID创建规则(唯一): 时间+5位随机数+用户id后四位+流水号
     *
     * @return
     */
    public String createOrderId(Integer uid) {
        StringBuffer buffer = new StringBuffer();

        //时间
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());

        //5位随机数 --->长度,是否含字符,是否含数字,全为false为乱码
        String random = RandomStringUtils.random(5, false, true);

        //用户id后四位
        String idStr = lastUserId(uid);

        // 流水号(不能重复)
        Long orderIndex = stringRedisTemplate.opsForValue().increment("order-index");

        return buffer.append(date).append(random).append(idStr).append(orderIndex).toString();
    }

    public String lastUserId(Integer uid) {
        StringBuffer buffer = new StringBuffer();
        String s = uid.toString();
        if (s.length() < 4) {
            //不足四位,id号前加0
            buffer.append(uid);
            for (int i = 0; i < 4 - s.length(); i++) {
                buffer.insert(0, "0");
            }
        } else {
            buffer.append(s.substring(s.length() - 4));
        }

        return buffer.toString();
    }
}
